﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GameClient;


namespace Submarines
{
    public partial class frmMain : Form
    {
        string _Oponent_user_name;
        List<string> _Users_list = new List<string>();
        List<string> _Users_list_old = new List<string>();
        //Timer _timer = new Timer();
        //int _max_val_for_timer = 30;
        //frmWait _wait_form = new frmWait();
        delegate void UserListCallback(string text);
        
        public frmMain()
        {
            InitializeComponent();
            GameClient.Client.RequestReceived += new Client.GameReceiveHandler(Client_RequestReceived);
            //GameClient.Client.GameAcceptAnswer += new Client.GameReceiveHandler(Client_GameAcceptAnswer); // TO REMOVE
            GameClient.Client.GameRequestAnswer += new Client.GameReceiveHandler(Client_GameRequestAnswer);
            GameClient.Client.OpenGameAnswer += new Client.GameReceiveHandler(Client_OpenGameAnswer);
            GameClient.Client.UsersListReceived += new Client.GameReceiveHandler(Client_UsersListReceived);
            lstUsersOnline.DataSource = _Users_list;
        }

        #region Local Events
        
        private void btnLocalGame_Click(object sender, EventArgs e)
        {
            Global._Local = true;
            frmGame game = new frmGame();
            game.ShowDialog();
            Global._Local = false;
        }

        private void btnAboutGame_Click(object sender, EventArgs e)
        { 
            SHDocVw.InternetExplorerClass ie = new SHDocVw.InternetExplorerClass();
            Object vHeaders = null;
            Object vPost = null;
            Object vTarget = null;
            Object vFlags = null;
            ie.Navigate("http://localhost:2889/SeaBattle/AboutGame.htm", ref vFlags, ref vTarget, ref vPost, ref vHeaders);
            ie.Visible = true;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Diag.AddLog(this.Name, "Form loaded");
            Lang.Language(this,typeof(frmMain));
            Diag.AddLog(this.Name, "Client.GetUsersList sent");
            GameClient.Client.GetUsersList();
            lblUserName.Text = Global._User_name;
            lblUserName.BackColor = Color.Transparent;
            lblListUsersOnLine.BackColor = Color.Transparent;
        }

        private void btnNewGame_Click(object sender, EventArgs e)
        {
            if (!lstUsersOnline.Items.Contains(Global._User_name))
            {
                Diag.AddLog(this.Name, "Client.OpenNewGame sent");
                GameClient.Client.OpenNewGame();
            }
            else
            {
                string _mess;
                if (Global._Language == "Русский")
                    _mess = "Такой пользователь уже существует в OnlineUsersLis";
                else if (Global._Language == "עברית")
                    _mess = "OnlineUsersLis " + "-" + "המשתמש כבר קיים ב";
                else
                    _mess = "User alredy exist in OnlineUsersList";

                MessageBox.Show(_mess);
            }
        }

        private void btnJoin_Click(object sender, EventArgs e)
        {
            if (lstUsersOnline.Items.Count > 0)
            {
                if (!lstUsersOnline.SelectedItem.ToString().Equals(""))
                {
                    _Oponent_user_name = lstUsersOnline.SelectedItem.ToString();
                    Diag.AddLog(this.Name, "Client.GameRequest sent to " + _Oponent_user_name);
                    GameClient.Client.GameRequest(_Oponent_user_name);
                    string _mess;
                    if (Global._Language == "Русский")
                        _mess = "Подключиться к игре";
                    else if (Global._Language == "עברית")
                        _mess = "להתחבר למשחק";
                    else
                        _mess = "Join Game";

                    //_Wait = new Wait(20, _mess);
                }
            }
        }

        //private void WaitWindowStart()
        //{
        //    if (!_timer.Enabled)
        //    {
        //        _timer.Tick += new EventHandler(_timer_Tick);
        //        _timer.Interval = 1000;
        //        _wait_form.Show();
        //        _timer.Start();
        //    }
        //    else MessageBox.Show("Lets wait for server answer!");
        //}
        //void _timer_Tick(object sender, EventArgs e)
        //{
        //    if (_max_val_for_timer >= 0)
        //    {
        //        _wait_form.lblWait.Text = ((_max_val_for_timer--).ToString());
        //    }
        //    else
        //    {
        //        _timer.Stop();
        //        _wait_form.Close();
        //        MessageBox.Show("No answer from server!");
        //    }
        //}

        private void listUsersOnline_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            btnJoin_Click(null, null);
        }

        #endregion

        #region Push_Events

        void Client_RequestReceived(object sender, ClientEventArgs e)
        {
            Diag.AddLog(this.Name, "Client_RequestReceived recieved from " + e.StringValue);
            string _mess1,_mess2;
            if (Global._Language == "Русский")
            {
                _mess1 = "Пользователь ";
                _mess2 = " ответил на ваше приглошение. Играть?";
            }
            else if (Global._Language == "עברית")
            {
                _mess1 = "?" + "ענה על בקשתך למשחק. עדיין רוצה לשחק איתו"+" ";
                _mess2 = " "+"משתמש";
            }
            else
            {
                _mess1 = "User ";
                _mess2 = " has requested for the game, do you want to play with him?";
            }

            DialogResult dr = MessageBox.Show(_mess1 + e.StringValue + _mess2, "SeaBattle", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            Diag.AddLog(this.Name, "Client.GameAccept " + dr.ToString() + " sent");
            if (dr == DialogResult.Yes)
            {
                GameClient.Client.GameAccept(Global._User_name, true);
            }
            else
            {
                GameClient.Client.GameAccept(Global._User_name, false);
            }
        }

        void Client_OpenGameAnswer(object sender, ClientEventArgs e)
        {
            Diag.AddLog(this.Name, "Client_OpenGameAnswer " + e.BoolValue.ToString() + " recieved");
            if (e.BoolValue)
            {
                Diag.AddLog(this.Name, "Client.GetUsersList sent");
                GameClient.Client.GetUsersList();
            }
        }

        void Client_GameRequestAnswer(object sender, ClientEventArgs e)
        {
            Diag.AddLog(this.Name, "Client_GameRequestAnswer " + e.BoolValue.ToString() + " recieved");
            //_Wait.CloseWindow();
            if (e.BoolValue)
            {
                Global._Opponent_name = e.StringValue;
                frmGame game = new frmGame();
                game.ShowDialog();
            }
            else
            {
                string _mess1, _mess2;
                if (Global._Language == "Русский")
                {
                    _mess1 = "Пользователь ";
                    _mess2 = " отклонил ваше приглошение.";
                }
                else if (Global._Language == "עברית")
                {
                    _mess1 = "לא אישר את המשחק שהיזמנת אותו" + " ";
                    _mess2 = " " + "משתמש";
                }
                else
                {
                    _mess1 = "User ";
                    _mess2 = " declined your request";
                }
                MessageBox.Show(_mess1 + Global._Opponent_name + _mess2);
            }
        }

        void Client_UsersListReceived(object sender, ClientEventArgs e)
        {
            UpdateUserList(e.StringValue);
        }

        #endregion

        #region Local_Func

        //void CloseWaitWindow()
        //{
        //    try
        //    {
        //        _timer.Stop();
        //        _wait_form.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }

        //}

       

        void UpdateUserList(string list)
        {
            if (this.InvokeRequired)
            {
                try
                {
                    UserListCallback d = new UserListCallback(UpdateUserList);
                    this.Invoke(d, new object[] { list });
                }
                catch (ObjectDisposedException)
                { }
            }
            else
            {
                string[] str_list = list.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                _Users_list.Clear();
                _Users_list.AddRange(str_list);

                if (!_Users_list_old.Equals(_Users_list))
                {
                    lstUsersOnline.DataSource = null;
                    lstUsersOnline.DataSource = _Users_list;
                    Diag.AddLog(this.Name, "Client_UsersListReceived " + str_list);
                }
                _Users_list_old = _Users_list;
            }
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            GameClient.Client.GetUsersList();
        }


    }
}
